package cn.toma.controller.others;

import cn.toma.common.exception.FfBootException;
import cn.toma.common.exception.RedisConnectException;
import cn.toma.common.utils.StringUtils;
import cn.toma.common.utils.web.CookieUtils;
import cn.toma.service.cache.RedisService;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author zqx
 * @version 1.0.0
 * @ClassName KaptchaController.java
 * @Description 验证码API
 * @createTime 2019年09月10日 16:34:00
 */
@Controller
@RequestMapping("/captcha")
public class CaptchaController
{

	static String COOKIE_NAME = "CaptchaCode";

	@Autowired
	private Producer producer;

	@Autowired
	private RedisService redisService;

	static long CAPTCHA_EXPIRES = 5 * 60 * 1000;

	/**
	 * 生成验证码
	 */
	@RequestMapping
	public void index(HttpServletRequest request, HttpServletResponse response) throws RedisConnectException
	{
		HttpSession session = request.getSession();

		response.setDateHeader("Expires", 0);

		// Set standard HTTP/1.1 no-cache headers.
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");

		// Set standard HTTP/1.0 no-cache header.
		response.setHeader("Pragma", "no-cache");

		// return a jpeg
		response.setContentType("image/jpeg");

		String uuid = UUID.randomUUID().toString();
		// 将验证码key，及验证码的图片返回
		// 新增到Cookie
		Cookie cookie = new Cookie(COOKIE_NAME, uuid);
		response.addCookie(cookie);

		// create the text for the image
		String capText = producer.createText();

		// store the text in the session
		session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

		// 将验证码以<key,value>形式缓存到redis
//		redisTemplate.opsForValue().set(uuid, capText, captchaExpires, TimeUnit.SECONDS);

		redisService.set(uuid, capText, CAPTCHA_EXPIRES);

		// create the image with the text
		BufferedImage bi = producer.createImage(capText);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// write the data out
		try {
			ImageIO.write(bi, "jpg", out);
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			try {
				out.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@RequestMapping("/check")
	@ResponseBody
	public Object checkCode(HttpServletRequest request, String code) throws FfBootException, RedisConnectException
	{
		String cookieValue = CookieUtils.getCookieValue(request, COOKIE_NAME);
		if (StringUtils.isEmpty(code) || StringUtils.isEmpty(cookieValue)) {
			throw new FfBootException("请输入验证码");
		}

		String redisCode = redisService.get(cookieValue);
		if (StringUtils.isEmpty(redisCode)) {
			throw new FfBootException("验证码过期");
		}
		if (redisCode.compareToIgnoreCase(code) != 0) {
			throw new FfBootException("验证码有误");
		}

		redisService.del(cookieValue);

		return "验证成功";
	}


}
